#!/bin/bash

################################################################################
# Tonys Director64 Video Converter
# Converts H.264 MOV to Director-compatible MPEG-4 MOV
################################################################################

clear
echo "╔════════════════════════════════════════════════════════════╗"
echo "║          Director Video Compatibility Converter            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Check for ffmpeg
if ! command -v ffmpeg &> /dev/null; then
    echo "❌ ffmpeg not found!"
    echo "This tool requires ffmpeg to convert videos."
    echo ""
    read -p "Install ffmpeg via Homebrew? [y/N]: " -n 1 -r
    echo ""
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        if ! command -v brew &> /dev/null; then
            echo "Installing Homebrew first..."
            /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
            if [ -f "/opt/homebrew/bin/brew" ]; then eval "$(/opt/homebrew/bin/brew shellenv)"; fi
        fi
        echo "Installing ffmpeg..."
        brew install ffmpeg
    else
        echo "Exiting. Cannot convert without ffmpeg."
        exit 1
    fi
fi

# Function to convert a single file
convert_file() {
    local input="$1"
    local ext="${input##*.}"
    local tmp_output="${input}.tmp.${ext}"
    
    echo "🎬 Converting: $(basename "$input")"
    
    # MPEG-4 conversion optimized for Director/QuickTime 7
    # Convert to temp file first
    ffmpeg -i "$input" -c:v mpeg4 -vtag mp4v -q:v 3 -c:a aac -b:a 192k -y "$tmp_output" 2>/dev/null
    
    if [ $? -eq 0 ]; then
        mv "$tmp_output" "$input"
        echo "✅ Success! Original file replaced with MPEG-4 version."
    else
        rm -f "$tmp_output"
        echo "❌ Failed to convert $(basename "$input")"
    fi
    echo "------------------------------------------------------------"
}

# Main loop
while true; do
    clear
    echo "╔════════════════════════════════════════════════════════════╗"
    echo "║          Director Video Compatibility Converter            ║"
    echo "╚════════════════════════════════════════════════════════════╝"
    echo ""
    echo "Select conversion mode:"
    echo "1) Select a specific file"
    echo "2) Convert all video files in this folder"
    echo "3) Exit"
    echo ""
    read -p "Choice [1-3]: " mode

    case $mode in
        1)
            while true; do
                # Use osascript to pick a file
                FILE_PATH=$(osascript -e 'POSIX path of (choose file with prompt "Select video file to convert" of type {"mov", "mp4", "m4v"})' 2>/dev/null)
                
                if [ -z "$FILE_PATH" ]; then
                    echo "No file selected. Returning to menu..."
                    sleep 1
                    break
                fi

                convert_file "$FILE_PATH"
                
                echo ""
                read -p "Convert another file? [y/N]: " -n 1 -r
                echo ""
                if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                    echo "Returning to menu..."
                    sleep 1
                    break
                fi
                clear
                echo "╔════════════════════════════════════════════════════════════╗"
                echo "║          Director Video Compatibility Converter            ║"
                echo "╚════════════════════════════════════════════════════════════╝"
                echo "Mode: Select Single File"
                echo "------------------------------------------------------------"
            done
            ;;
        2)
            clear
            echo "╔════════════════════════════════════════════════════════════╗"
            echo "║          Director Video Compatibility Converter            ║"
            echo "╚════════════════════════════════════════════════════════════╝"
            echo "Mode: Convert All in Folder"
            echo "------------------------------------------------------------"
            VIDEO_FILES=$(ls *.mov *.mp4 *.m4v 2>/dev/null)
            if [ -z "$VIDEO_FILES" ]; then
                echo "No compatible video files (.mov, .mp4, .m4v) found in current directory."
            else
                for file in $VIDEO_FILES; do
                    # Skip temp files if any exist
                    if [[ "$file" == *".tmp."* ]]; then continue; fi
                    convert_file "$file"
                done
                echo ""
                echo "✅ Batch conversion complete."
            fi
            read -p "Press Enter to return to menu..."
            ;;
        3)
            echo "Exiting..."
            break
            ;;
        *)
            echo "Invalid choice."
            sleep 1
            ;;
    esac
done

echo ""
echo "Program finished. Converted files are ready for Director."
echo ""
sleep 1
exit 0
